package com.laicunba.service.borrower.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.constant.GloabConstant;
import com.laicunba.pojo.BaseDO;
import com.laicunba.pojo.BorrowerDO;
import com.laicunba.pojo.JzhAccountDO;
import com.laicunba.pojo.JzhBorrowerRechargeOrderDO;
import com.laicunba.service.BorrowerService;
import com.laicunba.service.borrower.JzhBorrowerRechargeOrderService;
import com.laicunba.service.impl.BaseServiceImpl;
import com.laicunba.service.jzh.SecurityUtils;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.StringUtil;

@Service
public class JzhBorrowerRechargeOrderServiceImpl extends BaseServiceImpl implements JzhBorrowerRechargeOrderService {
	private static final Logger LOG = Logger.getLogger(JzhBorrowerRechargeOrderServiceImpl.class);
	private static final char SPLIT_CHAR = '|';
	@Autowired
	private BorrowerService borrowerService;


	@Transactional
	@Override
	public Result createNewOrder(BorrowerDO userDO, Long seq, BigDecimal amt) {

		Result result = new Result();

		JzhBorrowerRechargeOrderDO jzhBorrowerRechargeOrderDO = new JzhBorrowerRechargeOrderDO();
		String orderId = Long.toString(System.currentTimeMillis()) + StringUtil.randomNumber(7)
				+ String.format("%08d", seq);
		jzhBorrowerRechargeOrderDO.setId(orderId);
		jzhBorrowerRechargeOrderDO.setMchntTxnSsn(orderId);
		jzhBorrowerRechargeOrderDO.setPay(false);
		jzhBorrowerRechargeOrderDO.setAmt(amt.multiply(BigDecimal.valueOf(100)).intValue());
		jzhBorrowerRechargeOrderDO.setLoginId(userDO.getMobile());
		jzhBorrowerRechargeOrderDO.setUserId(userDO.getId());

		//返回地址临时处理，针对服务器https的控制
		String webPath = GloabConstant.WEB_PATH; 
		if(webPath.startsWith("http://")){
			webPath.replace("http://", "https://"); 
		}
		String backNotify = webPath + "/console/borrower/jzh_back_notify.htm";
		String pageNotify = webPath + "/console/borrower/jzh_page_notify.htm";
		StringBuilder signBuilder = new StringBuilder();
		signBuilder.append(Integer.toString(jzhBorrowerRechargeOrderDO.getAmt())).append(SPLIT_CHAR);
		signBuilder.append(backNotify).append(SPLIT_CHAR);
		signBuilder.append(jzhBorrowerRechargeOrderDO.getLoginId()).append(SPLIT_CHAR);
		signBuilder.append(GloabConstant.JZH_MCHNT_CD).append(SPLIT_CHAR);
		signBuilder.append(jzhBorrowerRechargeOrderDO.getMchntTxnSsn()).append(SPLIT_CHAR);
		signBuilder.append(pageNotify);
		result.setOrder(jzhBorrowerRechargeOrderDO);
		result.setBackNotify(backNotify);
		result.setPageNotify(pageNotify);
		result.setSignature(SecurityUtils.sign(signBuilder.toString()));
		AssertUtil.assertTrue(create(jzhBorrowerRechargeOrderDO), "CREATE_JZH_BORROWER_RECHARGE_ORDER_DO_FAIL");
		return result;
	}

	@Override
	public boolean verifyFromJzhServer(PayResult result) {
		StringBuilder signBuilder = new StringBuilder();
		signBuilder.append(result.getAmt()).append(SPLIT_CHAR);
		signBuilder.append(result.getLoginId()).append(SPLIT_CHAR);
		signBuilder.append(result.getMchntCd()).append(SPLIT_CHAR);
		signBuilder.append(result.getMcnntTxnSsn()).append(SPLIT_CHAR);
		signBuilder.append(result.getRem()).append(SPLIT_CHAR);
		signBuilder.append(result.getRespCode());
		return SecurityUtils.verifySign(signBuilder.toString(), result.getSignature());
	}

	@Transactional
	@Override
	public boolean onPaySuccess(PayResult result) {
		AssertUtil.assertNotNull(result, "RESULT_IS_NULL");
		AssertUtil.assertTrue("0000".equals(result.getRespCode()), "NOT_PAY_SUCCESS");
		AssertUtil.assertTrue(GloabConstant.JZH_MCHNT_CD.equals(result.getMchntCd()), "MCHNT_CD_NOT_MATCH");
		JzhBorrowerRechargeOrderDO orderDO = get(JzhBorrowerRechargeOrderDO.class, result.getMcnntTxnSsn());
		AssertUtil.assertNotNull(orderDO, "ORDER_NOT_EXIST");

		BorrowerDO userDO = borrowerService.get(BorrowerDO.class, orderDO.getUserId());
		AssertUtil.assertNotNull(userDO, "USER_NOT_EXIST");
		AssertUtil.assertTrue(userDO.getMobile().equals(result.getLoginId()), "LOGIN_ID_NOT_MATCH");

		if (orderDO.isPay()) {
			return true;
		}
		AssertUtil.assertTrue(result.getAmt() == orderDO.getAmt(), "AMT_NOT_MATCH");
		AssertUtil.assertTrue(updateDao.update("JZH_BORROWER_RECHARGE_ORDER.updatePaySuccess", orderDO.getId()) == 1,
				"UPDATE_PAY_STATUS_FAIL");
		
		//余额功能暂不做，先保留

//		BigDecimal balance = borrowerService.add(userDO.getId(),
//				BigDecimal.valueOf(result.getAmt()).divide(BigDecimal.valueOf(100)),
//				"recharge_" + result.getMcnntTxnSsn(), "recharge", "充值");
//		AssertUtil.assertNotNull(balance, "ADD_BALANCE_FAIL");
		return true;
	}

	@Override
	public List<JzhBorrowerRechargeOrderDO> findJzhRechargeList(String userId, int limit, int offset) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userId", userId);
		param.put("limit", limit);
		param.put("offset", offset);
		return queryDao.selectList("JZH_BORROWER_RECHARGE_ORDER.findJzhRechargeList", param);
	}
	
	@Override
	public boolean create(BaseDO entiry) {
		JzhBorrowerRechargeOrderDO jzhBorrowerRechargeOrderDO = (JzhBorrowerRechargeOrderDO) entiry;
		return super.create(jzhBorrowerRechargeOrderDO);
	}
}
